/**
 * 
 */
package net.phoenix.repository.query.jql;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import javax.jcr.RepositoryException;
import javax.jcr.Workspace;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.NodeTypeManager;
import javax.jcr.nodetype.PropertyDefinition;
import javax.jcr.query.InvalidQueryException;

import net.phoenix.repository.JCRUtils;
import net.phoenix.repository.dao.QDBName;

/**
 * @author lixf
 * 
 */
public class JQL2SQL {
	private static String[] reservedNames = { "id","name","parent","vindex"};
	private static String[] reservedColumns = { "node.pkid","node.name","node.parent_id", "node.vindex"};
	private Stack<String> sqlStack;

	private Stack<String> parameters;
	private NodeTypeManager manager;

	public JQL2SQL(NodeTypeManager manager) {
		this.sqlStack = new Stack<String>();
		this.parameters = new Stack<String>();
		this.manager = manager;
		//this.defaultType = null;
	}

	public String property2Column(String property) {
		if (this.isReserved(property))
			return this.convertReserved(property);
		//PropertyDefinition definition = JCRUtils.getPropertyDefinition(this.defaultType, property);
		//return QDBName.encode(property) + ".value";
		return "`"+property+"[0]`";
	}
	
	public String property2Column(String table, String property) throws NoSuchNodeTypeException, RepositoryException {
		if (this.isReserved(property))
			return this.convertReserved(property);
		//PropertyDefinition definition = JCRUtils.getPropertyDefinition(this.manager.getNodeType(table), property);
		//return QDBName.encode(definition.getRequiredType(), property) + ".value";
		return "`"+table+"."+property+"[0]`";
	}

	
	/**
	 * 
	 * @param property
	 * @return
	 */
	private boolean isReserved(String property){
		return Arrays.binarySearch(reservedNames, 0, reservedNames.length, property)>=0;
	}
	
	
	private String convertReserved(String property) {
		int index =  Arrays.binarySearch(reservedNames, 0, reservedNames.length, property) ;
		if(index>=0)
			return reservedColumns[index];
		return null;
	}


	public void push(String condition) {
		this.sqlStack.push(condition);
	}

	public String pop() {
		return this.sqlStack.pop();
	}

	public String getSQL() {
		return this.sqlStack.peek();
	}

	public void addParameter(String name) {
		this.parameters.add(name);
	}

	public String[] getParameters() {
		return this.parameters.toArray(new String[this.parameters.size()]);
	}

}
